<script setup lang="ts">
import { reactive, onMounted, ref } from 'vue'
import { useUserStore } from '@store/user'
import LoginRegisterOuter from '@components/login-register-outer/index.vue'
import { useRouter, useRoute } from 'vue-router'
import { login } from '@/api/user'
import { validateUserLogin } from '@/utils/user'
import type { UserLogin } from '@interface'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const userForm = reactive<UserLogin>({
  account: 'admin',
  password: 'admin',
})

const loading = ref(false)

const userAccountDisabled = ref(false)

// 检测是否携带账号
onMounted(() => {
  const query = route.query as { account?: string }
  if (!query.account) return
  userForm.account = query.account
  userAccountDisabled.value = true
})

// 登陆
const submit = async () => {
  const { val, key } = validateUserLogin(userForm)
  if (!val) throw new Error(`key -> ${key} is required!`)
  loading.value = true
  try {
    // 获取用户id
    const resp = await login(userForm)
    userStore.updateUserInfo(resp)
    loading.value = false
    router.push('/')
  } catch (e) {
    loading.value = false
  }
}

const toRegister = () => {
  router.push('/register')
}
</script>

<template>
  <LoginRegisterOuter
    @on-enter="submit"
    v-loading.fullscreen.lock="loading"
    element-loading-text="登陆中"
  >
    <ElInput
      placeholder="请输入账号"
      v-model.trim="userForm.account"
      :disabled="userAccountDisabled"
    />
    <ElInput
      placeholder="请输入密码"
      type="password"
      v-model.trim="userForm.password"
      show-password
    />
    <ElButton class="submit-button" type="primary" @click="submit">
      登陆
    </ElButton>
    <div class="to-button">
      <span @click="toRegister">去注册</span>
    </div>
  </LoginRegisterOuter>
</template>
